package com.wuxiaoqin.admin.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
import com.wuxiaoqin.admin.entity.Goodsstock;
import com.wuxiaoqin.admin.entity.goodParam.GoodsstockUpdate;
import com.wuxiaoqin.admin.mapper.GoodsstockMapper;
import com.wuxiaoqin.admin.service.IGoodsstockService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.wuxiaoqin.uitls.respObj.RespBean;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.List;

/**
 * <p>
 *  服务实现类
 * </p>
 *
 * @author jobob
 * @since 2021-11-08
 */
@Service
public class GoodsstockServiceImpl extends ServiceImpl<GoodsstockMapper, Goodsstock> implements IGoodsstockService {

    @Autowired
    private GoodsstockMapper goodsstockMapper;

    @Override
    public RespBean getGoodsStock(Integer goodsId) {
        Goodsstock goodsstock = goodsstockMapper.selectById(goodsId);
        goodsstock.setVersion(null);
        return RespBean.success("查询成功",goodsstock);
    }

    /**
     * 更改商品库存
     * @param goodsstockUpdate
     * @return
     */
    @Override
    public RespBean updateGoodsStock(GoodsstockUpdate goodsstockUpdate) {
        UpdateWrapper<Goodsstock> goodsstockUpdateWrapper = new UpdateWrapper<>();
        goodsstockUpdateWrapper.set("average", goodsstockUpdate.getAverage())
        .set("xs", goodsstockUpdate.getXs())
        .set("s", goodsstockUpdate.getS())
        .set("m", goodsstockUpdate.getM())
        .set("l", goodsstockUpdate.getL())
        .set("xl", goodsstockUpdate.getXl())
        .set("xxl", goodsstockUpdate.getXxl())
        .eq("C_id", goodsstockUpdate.getCId());

        int update = goodsstockMapper.update(null, goodsstockUpdateWrapper);

        if (update<0){
            RespBean.error("插入失败");
        }
        return RespBean.success("更改成功");
    }

    @Override
    public RespBean addOrSubtractStock(Integer goodsId, Boolean addOrSubtract, String size, Integer sum) {

        List<Object> stocklist = goodsstockMapper.selectObjs(new QueryWrapper<Goodsstock>().select(size).eq("C_id", goodsId));
        Integer stock = (Integer)stocklist.get(0);
        System.out.println(stock+"========");


        Goodsstock goodsstock = new Goodsstock();
        goodsstock.setCId(goodsId);
        int updateCount = 0;
        if (addOrSubtract){
            updateCount = goodsstockMapper.update(null,new UpdateWrapper<Goodsstock>().set(size, stock+sum).eq("C_id", goodsId));
        }else {
            if (stock < sum){
                return RespBean.error("您所减少的库存多于实际库存");
            }

            updateCount = goodsstockMapper.update(null,new UpdateWrapper<Goodsstock>().set(size, stock-sum).eq("C_id", goodsId));
        }
        if (updateCount <=0){
            return RespBean.error("库存修改失败");
        }
        return RespBean.success("修改成功");
    }
}
